# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, execjs
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "i康保·重大疾病"

    def genProductInfo(self):
        plan = {
            "planA":{
                # 年龄段
                "year": ["18-20", "21-25", "26-30", "31-35", "36-40", "41-45", "46-50"],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "300000", "500000"],
                # 交费方式
                "payType": ["年交", "月交"],
            },
            "planB":{
                # 年龄段
                "year": ["46-50"],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "300000"],
                # 交费方式
                "payType": ["年交", "月交"],
            }
        }
        for k in plan:
            for v in product( plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["payType"]):
                data = Helper.formatProductInfo( plan[k],v )
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(**data) )
    #执行爬虫
    def requestJson(self,dt=None,mysql=None):
        params = '''
        gender: F
        coverageAmount: 220000
        personAge: 27
        premType: 2
        socialSecurity: Y
        coverageLevel: 02
        '''
        data = Helper.perfectJson( params )
        data["gender"] = dt["gender"]
        if dt["money"] == "100000":
            coverageAmount = "220000"
        elif dt["money"] == "300000":
            coverageAmount = "660000"
        else:
            coverageAmount = "1100000"
        data["personAge"] = str(int(dt["year"].split("-")[0]) + 1)
        data["premType"] = "2" if dt["payType"] == "月交" else "1"
        data["coverageAmount"] = coverageAmount
        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "totalPrem" in r.text:
            price = Helper.decimalParse( r.json()["totalPrem"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])

